package ws.very.web.tpl.nutz
import org.nutz.mvc.adaptor.AbstractAdaptor
import java.lang.reflect.Type
import org.nutz.mvc.annotation.Param
import ws.very.web.adptor.SessionMap
import org.nutz.mvc.adaptor.ParamInjector
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.ServletContext
import org.nutz.mvc.adaptor.PairAdaptor
import ws.very.web.adptor.WebSessionMap
import ws.very.web.adptor.ApiSessionMap
import ws.very.web.adptor.ApiSessionMapMsg

trait HttpObjAdaptor extends AbstractAdaptor {
  override def evalInjector(typ: Type, param: Param) =
    typ match {
      case c: Class[_] if (classOf[WebSessionMap].isAssignableFrom(c)) => WebSessionMapInjector
      case c: Class[_] if (classOf[ApiSessionMap].isAssignableFrom(c)) => ApiSessionMdapInjector
      case c: Class[_] if (classOf[SessionMap].isAssignableFrom(c)) => AutoSessionMapInjector
      // case c: Class[_] if (classOf[RequestMap].isAssignableFrom(c)) => RequestMapInjector
      case _ => super.evalInjector(typ, param)
    }

}

class HttpObjPairAdaptor extends PairAdaptor with HttpObjAdaptor

object WebSessionMapInjector extends ParamInjector {
  override def get(sc: ServletContext, req: HttpServletRequest,
    resp: HttpServletResponse, refer: Object) =
    new WebSessionMap(req)
}
object Cons {
  val ApiUrlToken = "ws!ApiUrlToken"
}

object AutoSessionMapInjector extends ParamInjector {
  override def get(sc: ServletContext, req: HttpServletRequest,
    resp: HttpServletResponse, refer: Object) =
    if (req.getParameter(Cons.ApiUrlToken) != null)
      ApiSessionMapMsg.get(req.getParameter(Cons.ApiUrlToken))
    else
      new WebSessionMap(req)

}
object ApiSessionMdapInjector extends ParamInjector {
  override def get(sc: ServletContext, req: HttpServletRequest, resp: HttpServletResponse, refer: Object) =
    ApiSessionMapMsg.get(req.getParameter(Cons.ApiUrlToken))
}

